<?php

namespace App\Libs;

/**
 * 根据需求完善
 * 自定义定时器(作用于抑制所有定时器防止)
 * Class Timer
 * @package App\Libs
 */
class Timer
{
    private static $factory;

    /**
     * @param $time (时间)
     * @param $value (回调函数)
     * @param string $key (自定义键)
     * @param array $args
     * @param bool $persistent
     */
    public static function add($time, $value, $key = '',$args = array(),$persistent = true)
    {
        self::$factory[] = [
            'time' => $time,
            'value' => $value,
            'key' => $key,
            'handle' => __FUNCTION__,
            'args' => $args,
            'persistent' => $persistent
        ];
    }

    /**
     * @param $value )
     */
    public static function del($value)
    {


    }
    /**
     * 运行
     * @param string|array $key
     */
    public static function run($key = '')
    {
        foreach (self::$factory as $v) {
            if ($key && is_string($key)) {
                if ($v['key'] == $key) self::execute($v);
            } elseif ($key && is_array($key)) {
                if (in_array($v['key'], $key)) self::execute($v);
            } else {
                self::execute($v);
            }
        }
    }

    /**
     * 获取所有定时器(不做继承操作只获取最顶级的父级Timer)
     * @return mixed
     */
    public static function getAllTimer()
    {
        return self::$factory;
    }

    /**
     * 执行(once)
     * @param $v
     */
    private static function execute($v)
    {
        $handle = $v['handle'];
        \Workerman\Lib\Timer::$handle($v['time'], function ($args) use ($v) {
            return $v['value']($args);
        },['args'=>$v['args']],$v['persistent']);
    }
}
